package accountandrole

import (
	//"fmt"
	"jiabo/appframework/libs/db"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

type Role struct {
	Id        bson.ObjectId `bson:"_id,omitempty" json:"-"`
	RoleName  string        `bson:"roleName" json:"roleName"`
	Desc      string        `bson:"desc" json:"desc"`
	Belongsto []Role        `bson:"belongsto" json:"belongsto"`
}

func (role *Role) CheckIfroleExist() (result bool, searchErr error) {
	searchErr = nil
	searchResults := Role{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"roleName": role.RoleName}).One(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("roles", query)
	}
	err := search()
	if err != nil {
		searchErr = err
	}

	if searchResults.Id != "" {
		result = true
	} else {
		result = false
	}
	return
}

func (role *Role) Save() error {
	ifRoleExist, err := role.CheckIfroleExist()
	if err != nil {
		return err
	}
	if ifRoleExist {
		update := func(c *mgo.Collection) error {
			fn := c.Update(bson.M{"roleName": role.RoleName}, role)
			return fn
		}

		updateExec := func() error {
			return db.WithCollection("roles", update)
		}

		err := updateExec()
		return err
	} else {
		insert := func(c *mgo.Collection) error {

			fn := c.Insert(role)
			return fn
		}

		insertExec := func() error {
			return db.WithCollection("roles", insert)
		}

		err := insertExec()
		return err
	}
	return nil
}

func (role *Role) Delete() error {
	ifRoleExist, err := role.CheckIfroleExist()
	if err != nil {
		return err
	}
	if ifRoleExist {
		delet := func(c *mgo.Collection) error {
			fn := c.Remove(bson.M{"roleName": role.RoleName})
			return fn
		}

		deleteExec := func() error {
			return db.WithCollection("roles", delet)
		}

		err := deleteExec()
		return err
	}
	return nil
}

// func (role *Role) GetAllAccountInRole() (accounts []Account, err error) {
// 	err = nil

// }

func GetRoleByUserName(roleName string) (role Role, searchErr error) {
	searchErr = nil
	searchResults := Role{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"roleName": roleName}).One(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("roles", query)
	}
	err := search()
	if err != nil {
		searchErr = err
		return
	}

	if searchResults.Id != "" {
		role = searchResults
		return
	}
	return
}
